package com.chee.plant.server;

import org.apache.mina.common.ByteBuffer;
import org.apache.mina.common.IoSession;
import org.apache.mina.filter.codec.CumulativeProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;

public class MessageDecoder extends CumulativeProtocolDecoder {
	@Override
	protected boolean doDecode(IoSession session, ByteBuffer in, ProtocolDecoderOutput out) throws Exception {
		return true;
//		if (in.prefixedDataAvailable(4)) {
//			int totalSize = in.getInt();
//			byte[] total_bytes = new byte[totalSize];
//			in.get(total_bytes);
//            Message msg = new Message();
//			byte[] tmp = this.clipByte(total_bytes, 0, 4);
//            int userId = this.byte2int(tmp);
//            msg.setUserId(userId);
//            tmp = this.clipByte(total_bytes, 4, 4);
//            int cmdInt = this.byte2int(tmp);
//            PlantCmd command = PlantCmd.getCmd(cmdInt);
//            msg.setCommand(command);
//            tmp = this.clipByte(total_bytes, 8, 4);
//            int result = this.byte2int(tmp);
//            msg.setResult(result);
//            tmp = this.clipByte(total_bytes, 12, 4);
//            int flag = this.byte2int(tmp);
//            msg.setFlag(flag);
//            tmp = this.clipByte(total_bytes, 16, 4);
//            int contentSize = this.byte2int(tmp);
//            tmp = this.clipByte(total_bytes, 20, contentSize);
//            byte[] _crc = this.clipByte(total_bytes, 20+contentSize, 8);
//            long crc = this.byte2long(_crc);
//            boolean crcChk = msg.setContent(tmp,crc);
//            if(!crcChk){ CommonData.getLogger().error("Wrong CRC"); }
//            else{
//	            msg.setSession(session);
//	            out.write(msg);
//            }
//            return true;
//        } else {
//            return false;
//        }
	}
	public byte[] clipByte(byte[] array, int offset, int length){
		byte[] bytes = new byte[length];
		for(int i=0;i<length;i++){
			bytes[i] = array[i+offset];
		}
		return bytes;
	}
	public int byte2int(byte[] res) {
		long result = 0;
		for(int init=3,i=3; i>=0; i--){
			result = result | ((long)((res[i] & 0xFF)) << (8*(init-i)));
		}
		return new Long(result).intValue();
	}
	public long byte2long(byte[] res) {
		long result = 0;
		for(int init=7,i=7; i>=0; i--){
			result = result | ((long)((res[i] & 0xFF)) << (8*(init-i)));
		}
		return result;
	}
	public static void main(String[] args){
		MessageDecoder de = new MessageDecoder();
		byte[] a = new byte[]{0, 0, 0, 0, -32, 54, -62, 101};
//		byte[] aa = new byte[]{-32, 54, -62, 101};
		long b = de.byte2long(a);
//		//System.out.println(a);
		System.out.println(b);
	}
}
